define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');
	var adx_map = pubjs.config('channelMap');

	var Ads = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'view_model': {
					'showAdd': false
				}
			});

			this.$type = 0;
			this.$channelId = null;
			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			// var c = self.getConfig();
			self.append($([
				'<div class="M-formHead">',
					'<span class="M-formHeadTitle">'+LANG('广告位报表')+'</span>',
					'<span ms-visible="showAdd" class="ml10" pub-name="add" pub-mod="@base/common/drop.add"></span>',
					'<span class="ml10 addButton" pub-name="addButton" pub-mod="@base/common/drop.add"></span>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="ads/grid/list.ads"/>'
			].join('')));

			var config = {
				grid: {
					param: {
						'Type': self.$type,
						'IsDeleted': 0,
						'isRTB': true
					},
					hasMenu: true,
					auto_load: false,
					hasBatch: true,
					hasSelect: true,
					eventDataLoad: true,
					hasAutoRefresh: true
				},
				date:{
					pos: 'bR'
				},
				add:{
					def: LANG('新建广告位'),
					href: '#ads/add'
				},
				addButton: {
					'options': [
						{
							'id': 2,
							'name': LANG('媒体资源'),
							'href':"#ads/priceList",
							'target':"_blank",
							'icon': 'icon-setting2'
						},
						{
							'id': 1,
							'name': LANG('广告位分组'),
							'href':"#ads/adsGroup",
							'target':"_blank",
							'icon': 'icon-setting2'
						}
					]
				}
			};
			self.buildFromTemplate(config);

			self.buildSidebar();
		}
		,buildSidebar: function(){
			var self = this;
			var c = self.getConfig();
			self.createAsync('sidebar', '@layout/v1/sidebar.base', {
				'target': c.targetSidebar,
				'items': [
					{'name': 'type', 'uri':'modules/sideBarBase.campaignType', type: 'spot'},
					{'name': 'channel', 'uri':'modules/sideBarBase.channel', config: {filterAccess: true}},
					{'name': 'cost', 'uri':'modules/sideBarBase.costType'},
					{'name': 'group', 'uri':'modules/sideBarBase.adsGroupPop'},
					{'name': 'metrics', 'uri':'modules/sideBarBase.metrics', 'config': {
						'metrics': ["{front}","{back}","{conversion}","{cost}"]
					}}
				]
			}, function(){
				self.get('sidebar/cost').hide();
			});
		}
		,afterBuildTemplate: function(){
			var self = this;
			// 列表构建完，默认以一个渠道加载
			if(self.get('sidebar/channel')){
				//self.get('sidebar/channel').setValue(pubjs.config('pcChannel')[0].id);
				//self.get('sidebar/channel').setAll();
				self.get('sidebar').save();
			}
		}
		,onSidebarFilterGroup: function(ev){
			var self = this;
			var id = ev.param.id;
			switch (ev.name){
				case 'type':
					if(self.get('sidebar/group')){
						self.get('sidebar/group')
						[id == 2 ? 'hide' : 'show']();
						// .setParam({
						// 	'Type': id == 1 ? 'pc': 'mobile'
						// }).load();
					}
					if(self.get('sidebar/channel')){
						if(id == 2){
							self.get('sidebar/channel').setAll();
						}
					}
					break;
				case 'channel':
					if(self.get('sidebar/group')){
						self.get('sidebar/group').setParam({
							'ChannelId': id
						}).load();
					}

					break;
			}
			return false;
		}
		,onSidebarFilter: function(ev){
			var self = this
				,param = {};

			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;

				switch (type) {
					case 'type':
						self.$.grid[id == 2 ? 'disableChild' : 'enableChild']('batch');
						param.Type = +id;
						param.cost = 0;
						param.isRTB = (id !== 2);
						self.filterChange(+id);
						self.$type = +id;
						break;
					case 'channel':
						self.$channelId = +id;
						param.ChannelId = +id;
						break;
					case 'group':
						param.PositionCategoryIds = +id;
						break;
					case 'metrics':
						param.metrics_filter = id;
						break;
					case 'cost':
						param.cost = +id;
						break;
				}
			});

			self.reload(param);
		}
		,filterChange: function(type) {
			var self = this;
			// 广告监测显示新增按钮
			self.vm.setItem('showAdd', type == 2);
			if(self.$.grid){
				// 广告监测显示操作列
				self.$.grid.toggleColumn('op', type == 2);
			}
		}
		,onGridDataLoad: function() {
			if(this.$.grid && this.$.grid){
				this.$.grid.toggleColumn('op', this.$type == 2);
			}
			return false;
		}
		// 批量操作-下拉菜单界面
		,onBatchShow: function(ev){
			var self = this;
			var text;
			if(self.$type == 2){
				text = LANG('广告监测是没有批操作的');
			}
			else {
				if(!self.$channelId)
				{
					text = LANG('显示所有渠道的情况下,该功能无法使用');
				}
				else {
					var op = [];
					ev.returnValue = op;
					if(pubjs.checkRight('spot.batchExport')) {
						op.push({name: LANG('导出选中广告位'), id: 'export'});
					}
					if(pubjs.checkRight('spot.batchAttachCampaign')) {
						op.push({name: LANG('附加到活动'), id: 'attachCampaign'});
					}
					if(pubjs.checkRight('spot.batchCreateGroup')) {
						op.push({name: LANG('创建广告位分组'), id: 'createGroup'});
					}
					return false;
				}
			}

			if(text) {
				var tips = self.$.tips;
				if(!tips) {
					self.createAsync('tips', '@base/tip.base', {
						anchor: ev.from.$el,
						width: 120,
						height: 60
					}, function(mod){
						mod.setData(text);
					});
				}
				else {
					tips.setData(text);
					tips.show();
				}
			}

			return false;
		}
		// 批量操作-响应菜单操作
		,onBatchSelect: function(ev){
			var self = this;
			var data = ev.param[0];
			var ids = ev.param[1];
			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择对应的广告位'));
				return false;
			}

			switch(data.key){
				case 'export':
					self.exportAdd(ids.join());
					break;
				case 'attachCampaign':
					self.attachCampaign(ids);
					break;
				case 'createGroup':
					self.createGroup(ids);
					break;
			}

			return false;
		}
		,createGroup: function(ids) {
			var createMod = this.$.createGroup;
			var param = {
				'AdxId': this.$channelId,
				'Spots': {
					'PositionIds': ids
				}
			};		
			
			if (!createMod)
			{
				this.createAsync('createGroup', 'ads/popwin/createGroup.base', {}, function(mod)
				{
					mod.reset().setParam(param).show();
				});
			}
			else
			{
				createMod.reset().setParam(param).show();
			}
		}
		,attachCampaign: function(ids) {
			var self = this;
			var mod = self.$ && self.$.attachPop;
			var param = {
				ChannelId: self.$channelId
				,ids: ids
			};
			if(!mod) {
				this.createAsync('attachPop', 'ads/popwin/list.attachCampaign', function(mod){
					mod.setParam(param).load();
					mod.show();
				})
			}
			else {
				mod.setParam(param).load();
				mod.show();
			}
		}
		// 批处理的导出框
		,exportAdd: function(ids) {
			var self = this;
			var type = self.$type;
			var channelId = self.$channelId;
			var url = type != 2 ? 'spot/listByIds': 'spot/monitorList';
			pubjs.mc.send(url, {ChannelId: channelId, ids: ids, decimal: true}, function(err, data) {
				if(err) {
					pubjs.alert(err.message);
					return false;
				}
				var code = '';
				util.each(data.items, function(spot){
					var width = Math.floor(spot.Size /10000);
					var height = spot.Size % 10000;
					code += [spot.decimal_id, width+'*'+height, spot.Name].join('\t\t') + '\n';
				});

				var pop = self.$ && self.$.exportPop;
				var title = LANG('广告位选择导出导入 -- 渠道 : ') + (adx_map[channelId] || LANG('未知'));
				if(pop) {
					pop.setTitle(title).setData(code).show();
				}
				else {
					self.createAsync('exportPop', 'modules/port.export', function(mod){
						mod.setTitle(title).setData(code).show();
					});
				}
			});
		}
		// 操作菜单-下拉菜单界面
		,onOperateMenuShow: function(ev){
			var op = [];
			ev.returnValue = op;

			if(pubjs.checkRight('spot.info')) {
				op.push({name: LANG('编辑'), id: 'edit'});
			}

			if(pubjs.checkRight('spot.remove')) {
				op.push({name: LANG('删除'), id: 'remove'});
			}
			return false;
		},
		// 操作菜单-响应菜单操作
		onOperateMenuSelect: function(ev){
			var op = ev.param[0]; // 按钮信息：{key: 1, name: '开始'}
			var data = ev.param[1];
			var self = this;
			switch(op.key){
				case 'edit':
					window.open('#ads/edit/' + data._id );
					break;
				case 'remove':
					// pubjs.alert('真的要删除这个广告位吗？');
					pubjs.confirm(LANG('确认删除广告位 %1 吗', +data._id), function(state) {
						if(state)
						{
							pubjs.loading.show();
							pubjs.mc.send('spot/remove', {'_id': +data._id }, function(err) {
								pubjs.loading.hide();
								if(err)
								{
									return pubjs.alert(err.message);
								}

								pubjs.alert(LANG('删除成功'));
								self.reload();
							});
						}
					});
					break;
			}
			return false;
		},
		reload: function(param) {
			this.$.grid.reload(param);
		}
	});
	exports.ads = Ads;

	exports.media = Ads.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'urlRemove': 'massMedia/remove'
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.append($([
				'<div class="M-formHead">',
					'<span class="M-formHeadTitle">'+LANG('媒体报表')+'</span>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="ads/grid/list.media"/>'
			].join('')));

			var config = {
				grid: {
					param: {
						'Type': 0
					},
					hasSelect: true,
					eventDataLoad: true,
					hasSearch: true,
					gridName: 'media'
				},
				date:{
					pos: 'bR'
				}
			};
			self.buildFromTemplate(config);
			self.buildSidebar();
		}
		// 操作菜单-下拉菜单界面
		,onOperateMenuShow: function(ev){
			var op = [];
			ev.returnValue = op;

			op.push({name: LANG('广告位管理'), id: 'adM'});
			op.push({name: LANG('频道管理'), id: 'chM'});
			if(pubjs.checkRight('spot.info') || 1) {
				op.push({name: LANG('编辑'), id: 'edit'});
			}

			if(pubjs.checkRight('spot.remove') || 1) {
				op.push({name: LANG('删除'), id: 'remove'});
			}
			return false;
		},
		// 操作菜单-响应菜单操作
		onOperateMenuSelect: function(ev){
			var op = ev.param[0]; // 按钮信息：{key: 1, name: '开始'}
			var data = ev.param[1];

			switch(op.key){
				case 'edit':
					this.editMediaSpot(data);
					break;
				case 'remove':
					this.removeMediaSpot(data);
					break;
				case 'adM':
					pubjs.controller.navigate('ads/adPositions/' + data._id );
					break;
				case 'chM':
					pubjs.controller.navigate('ads/adChannels/' + data._id );
					break;
			}
			return false;
		},
		// 编辑广告监测媒体
		editMediaSpot: function( data ) {
			var self = this;
			var mod = self.$ && self.$.editMediaPop;
			if(!mod) {
				this.createAsync('editMediaPop', 'ads/popwin/list.editMediaSpot', function(mod){
					mod.setData(data);
					mod.show();
				})
			}
			else {
				mod.setData(data);
				mod.show();
			}
		},
		onMediaSaveSuccess: function() {
			this.$.grid.reload();
			return false;
		},
		// 删除广告监测媒体
		removeMediaSpot: function( data ) {
			pubjs.mc.send(
				this.getConfig('urlRemove'),
				{
					'_id': data._id
				},
				this.onRemove.bind( this )
			)
		},
		onRemove: function( err ) {
			if( err ) {
				pubjs.alert(err.message);
				return false;
			}
			this.$.grid.reload();
		}
	});

	exports.size = Ads.extend({
		init:function(config){
			config = pubjs.conf(config, {
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.append($([
				'<div class="M-formHead">',
					'<span class="M-formHeadTitle">'+LANG('尺寸报表')+'</span>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="ads/grid/list.mainSize"/>'
			].join('')));

			var config = {
				grid: {
					param: {
						'Type': 0
					},
					hasSelect: true,
					eventDataLoad: true,
					hasSearch: true,
					gridName: 'size'
				},
				date:{
					pos: 'bR'
				}
			};
			self.buildFromTemplate(config);
			self.buildSidebar();
		}
	});

	// 广告位管理 by TBC
	exports.adPositions = Ads.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'urlRemove': 'spot/remove'
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			this.append($([
				'<div class="M-formHead">',
					'<span class="M-formHeadTitle">'+LANG('广告位管理')+'</span>',
					'<span class="ml10 addButton" pub-name="addAdsButton" pub-mod="@base/common/drop.add"></span>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="ads/grid/adPositions.base"/>'
			].join('')));

			this.buildFromTemplate({
				'grid': {
					'hasSearch': true
				},
				'addAdsButton': {
					'def': LANG('添加广告位'),
					'href': '#ads/add'
				}
			});

			this.createAsync('editSpotPop', 'ads/popwin/list.editSpot');
		},
		// 添加广告位
		onInputClick: function( ev ) {
			return false;
		},
		// 操作菜单-响应菜单操作
		onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var data = ev.param[1];
			switch(op.key){
				case 'edit':
					this.showEditPop(data);
					break;
				case 'remove':
					this.removeAds(data);
					break;
			}
			return false;
		},
		showEditPop: function( data ) {
			var self = this;
			var mod = self.$ && self.$.editSpotPop;
			mod.setData(data);
			mod.show();
		},
		removeAds: function( data ) {
			pubjs.mc.send(
				this.getConfig('urlRemove'),
				data,
				this.onRemoveAds.bind(this)
			);
		},
		onRemoveAds: function( err, data ) {
			if( err ) {
				pubjs.alert(err.message);
				return false;
			}
			this.$.grid.reload();
		},
		// 编辑更新成功
		onSpotUpdateSuccess: function() {
			this.$.grid.reload();
			return false;
		},
		load: function( id ) {
			this.$.grid.setParam({
				'MassMediaId': id
			}).reload();
		}
	});

	// 频道管理 by TBC
	exports.adChannels = Ads.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'url': 'massChannel/remove'
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			this.append($([
				'<div class="M-formHead">',
					'<span class="M-formHeadTitle">'+LANG('频道管理')+'</span>',
					'<span class="ml10 addButton" pub-name="addButton" pub-mod="@base/common/drop.add"></span>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="ads/grid/adChannels.base"/>'
			].join('')));

			this.buildFromTemplate({
				'grid': {
					'hasSearch': true
				},
				'addButton': {
					'def': LANG('添加频道')
				}
			});

			this.createAsync('editChannelPop', 'ads/popwin/list.aeChannel');
		},
		// 添加频道
		onInputClick: function( ev ) {
			this.showAddPop();
			return false;
		},
		// 操作菜单-响应菜单操作
		onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var data = ev.param[1];
			switch(op.key){
				case 'edit':
					this.showEditPop(data);
					break;
				case 'remove':
					this.removChannels(data);
					break;
			}
			return false;
		},
		showAddPop: function() {
			this.showEditPop();
		},
		showEditPop: function( data ) {
			var self = this;
			var mod = self.$ && self.$.editChannelPop;
			if( data ) {
				data.action = 'edit';
				data.MassMediaId = self.$id;
			}
			else {
				data = {
					'MassMediaId': self.$id,
					'action': 'add'
				}
			}
			mod.setData(data);
			mod.show();
		},
		removChannels: function( data ) {
			pubjs.mc.send(
				this.getConfig('url'),
				{
					'_id': data._id
				},
				this.onRemoveChannels.bind(this)
			);
		},
		onRemoveChannels: function( err, data ) {
			if( err ) {
				pubjs.alert(err.message);
				return false;
			}
			this.$.grid.reload();
		},
		load: function( id ) {
			this.$id = +id;
			this.$.grid.setParam({
				'MassMediaId': +this.$id
			}).reload();
		},
		onChannelSaveSuccess: function() {
			this.$.grid.reload();
			return false;
		}
	});

});